import axios from 'axios';
import router from '../router'

// 做axios拦截
// 添加请求拦截器
axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('_token')
  if (token) {
    config.headers.authorization = `Bearer ${token}`
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

axios.interceptors.response.use((response) => {
  const { code, message } = response.data;
  if (code === -1) {
    window.antd.message.error(`验证未通过 -> ${message}`);
  } else if (code === 0) {
    window.antd.message.error(`错误 -> ${message}`);
  }

  return response;
}, (error) => {
  if (error.response) {
    const status = error.response.status
    if (status === 401) {
      window.antd.message.error('未登录 或 已失效...')
      localStorage.removeItem('_token')
      setTimeout(() => {
        router.push('/login')
      }, 1000);
    }

    if (status === 403) {
      window.antd.message.error('拒绝访问')
    }

    if (status === 404) {
      window.antd.message.error('您访问的页面不存在')
    }

    if (status === 500) {
      window.antd.message.error('服务器内部错误，请联系管理员')
    }
  }

  return Promise.reject(error);
})

function request({
  method,
  url,
  data,
  params
}) {
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      data,
      params
    })
      .then(res => {
        resolve(res.data);
      })
      .catch(error => {
        reject(error.response)
      })
  })
}

export default request;